package com.example.interceptor;

import com.example.vo.response.UserDTO;
import com.example.utils.JwtUtil;
import com.example.utils.UserHolder;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.time.Instant;


/**
 * 除请求"/user/login"，"/user/register"，"/user/getAuthCode/*", "/user/resetPassword" 外的请求，进入登录拦截器拦截方法
 * 登录校验，访问接口时，从请求头中获取token,如果请求头中没有token或token过期，则返回401（拦截器拒绝）
 * 存储用户信息到ThreadLocal中
 */

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("authorization");


        if (token == null) {
            response.setStatus(401);
            return false;
        }

        try {
            // 解析JWT
            Claims claims = JwtUtil.parseJwt(token);
            // 获取JWT过期时间
            Instant expiration = claims.getExpiration().toInstant();
            // 检查是否过期
            Duration duration = Duration.between(Instant.now(), expiration);
            long minutesRemaining = duration.toMinutes();

            if (minutesRemaining < 10) {
                // JWT已过期，执行过期处理逻辑
                response.setStatus(401);
                return false;
            } else {
                // JWT未过期，执行正常逻辑
                // 获取执行操作用户信息存入ThreadLocal中
                String userId = claims.getSubject();

                UserDTO userDTO = (UserDTO) request.getSession().getAttribute("user" + userId);

                if (userDTO == null) {
                    response.setStatus(401);
                    return false;
                }

                UserHolder.saveUser(userDTO);

                // TODO 刷新jwt过期时间

                return HandlerInterceptor.super.preHandle(request, response, handler);
            }
        } catch (ExpiredJwtException e) {
            // JWT已过期，执行过期处理逻辑
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
